package com.zrf.base.knowledge.classload.classLoader;

import java.io.InputStream;

/**
 * 自定义符合双亲委派模型classLoader
 * @author zhouruifeng
 * Created by zhouruifeng on 2018/4/11.
 */
public class ParentsDelegateCustomClassLoaderTest {
    public static void main(String[] args) throws ClassNotFoundException, IllegalAccessException, InstantiationException {
        ClassLoader classLoader = new ClassLoader() {
            @Override
            protected Class<?> findClass(String name) throws ClassNotFoundException {
                try {
                    String fileName = name.substring(name.lastIndexOf(".") + 1) + ".class";
                    InputStream resourceAsStream = getClass().getResourceAsStream(fileName);
                    if (resourceAsStream == null) {
                        return super.loadClass(name);
                    }
                    byte[] bytes = new byte[resourceAsStream.available()];
                    resourceAsStream.read(bytes);
                    return defineClass(name, bytes, 0, bytes.length);
                } catch (Exception e) {
                    throw new ClassNotFoundException(name);
                }
            }
        };
        Object obj = classLoader.loadClass(ParentsDelegateCustomClassLoaderTest.class.getName()).newInstance();
        System.out.println(obj.getClass());
        System.out.println(obj instanceof ParentsDelegateCustomClassLoaderTest);
    }
}
